package com.rj.bd.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.annotations.Param;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import com.rj.bd.entity.User;
import com.rj.bd.service.IUserService;
import com.rj.bd.utils.CodeUtils;
import com.rj.bd.utils.RedisUtils;


import redis.clients.jedis.Jedis;



/**
 * 
 * @author Administrator
 *
 */
@RestController
public class UserController {
	
	//使用win10本机的redis
	static Jedis jedis = RedisUtils.getJedis();
	
	@Autowired   //注入
	public IUserService userService;
	
	
	
    /**
     * 注册生成获取验证码
     */
    @RequestMapping(value="/user/saveToken",produces={"application/json;charset=UTF-8"})//标识方法名称
    @ResponseBody
    @CrossOrigin(origins = "*", maxAge = 3600)
    public Map<String,Object> saveToken(HttpServletRequest request){
        
        Map<String, Object> map=new HashMap<String, Object>();

        System.out.println("--------------模拟给用户发送注册验证码---------------------");
        //String codeV= String.valueOf(Math.round(Math.random() * (9999-1000) +1000));//生成四位数字
        String yanzhengma= CodeUtils.createCode();
        System.out.println("生成的验证码为:"+yanzhengma);
        //token:是redis中验证码的key值

        System.out.println("判断一下这个验证码是否存在redis中");
        Boolean tokenIsExists = jedis.exists("token");//判断一下这个验证码是否存在redis中

        //先进行懒惰删除
        System.out.println("先进行懒惰删除");
        if(tokenIsExists){
            jedis.del("token");//如果验证码存在就通过del()函数主动的去实现惰性删除
            System.out.println("如果验证码存在就通过del()函数主动的去实现惰性删除");
        }

        //然后进行定期删除
        /*
         * NX：key不存在时才set，
         * EX：代表设定的是秒，
         * 60：代表60秒
         *
         * 友情提示：此时你进入redis-cli --raw  通过指令get token 即可查看到验证码，然后在通过指令 ttl token 即可看到剩余时间
         *
         * */
        long time=60;
        System.out.println("执行添加set且token的值为:"+yanzhengma);
        jedis.set("token",yanzhengma,"NX","Ex",time);
        System.out.println("注册验证码发送成功");

        map.put("code", 0);
        map.put("msg", "验证码获取成功");
        map.put("data",yanzhengma);
        map.put("time",time);
        return map;
    }
	
	
	 /**
     * @desc user的登录模块
     */
	@RequestMapping(value="/user/login",produces={"application/json;charset=UTF-8"})//标识方法名称
	@ResponseBody
	@CrossOrigin(origins = "*", maxAge = 3600)
    public Map<String,Object> login( @Param("unumber")String unumber, @Param("upassword")String upassword,HttpServletRequest request) {

    System.out.println("进入登录方法///////////////////////");
       System.out.println(unumber);
       System.out.println(upassword);
        String yanzhengma = request.getParameter("yanzhengma");
        System.out.println("用户账号：" + unumber + "用户密码：" + upassword);

        Map<String, Object> map = new HashMap<String, Object>();
        if (unumber == null || unumber.equals("")) {
            map.put("login", 0);
            map.put("msg","请输入账号");
            return map;
        }
        if (upassword == null || upassword.equals("")) {
            map.put("login", 1);
            map.put("msg","请输入密码");
            return map;
        }
        if (yanzhengma == null || yanzhengma.equals("")) {
            map.put("login", 2);
            map.put("msg", "验证码为空，请重新获取");
            return map;
        }


        String tokenYanzhengma = jedis.get("token");//从redis中获取的验证码

        //判断验证码
        if (tokenYanzhengma != null) {
            System.out.println("缓存没有失效(验证码没有过期/失效)，用户可以注册");
            if (yanzhengma.equals(tokenYanzhengma) || yanzhengma == tokenYanzhengma) {
                System.out.println("输入的验证码正确，注册成功");
                User user = userService.login(unumber, upassword);
                if (user == null) {
                    map.put("login", "0");
                    return map;
                }

                map.put("login", 3);
                map.put("code", 0);
                map.put("data", user);
                System.out.println("用户账号:" + unumber);
                System.out.println("用户密码:" + upassword);
                return map;
            } else {
                System.out.println("输入的验证码错误，请重新输入验证码");
                map.put("login", "0");
                map.put("msg", "输入的验证码错误，请重新输入验证码");
                return map;
            }
        } else {
            System.out.println("缓存已经失效,请重新获取验证码");
            map.put("login", "0");
            map.put("msg", "缓存已经失效,请重新获取验证码");
            return map;
        }


    }
	
	
	
	/**
	 * 查询全部
	 * @param request
	 * @return
	 */
    @RequestMapping(value="user/queryAll",produces={"application/json;charset=UTF-8"})//标识方法名称
    @ResponseBody
    @CrossOrigin(origins = "*", maxAge = 3600)	  
    public Map<String, Object> queryAll(HttpServletRequest request) {
        System.out.println("UserController--->queryAll()");

        Map<String, Object> map = new HashMap<String, Object>();

        List<User> list = userService.queryAll();
    
        System.out.println("长度为:" + list.size());

        map.put("code", 0);
        map.put("msg", "查询成功");
        map.put("count", list.size());
        map.put("data", list);
        return map;
    }
	
	
    /**
     * 分页&条件查询
     */
    @RequestMapping(value="/user/query",produces={"application/json;charset=UTF-8"})//标识方法名称
	@ResponseBody
	@CrossOrigin(origins = "*", maxAge = 3600)
    public Map<String,Object>query(@RequestParam Map maps){
        System.out.println("UserController--->query()");
        List<Map> Page=userService.getPage(maps);
        List<User>list=userService.queryAll();
        int count=list.size();
        Map<String, Object> map = new HashMap<String, Object>();
        // System.out.println("---"+count);
        // System.out.println("pageNo---"+maps.get("pageNo")+"pageSize---"+maps.get("pageSize"));
        map.put("count",count);
        map.put("code", 0);
        map.put("msg", "");
        map.put("data", Page);
        return map;
    }
    
   
    /**
     * 根据id查状态
     */
    @RequestMapping(value="/user/queryByUid")//标识方法名称
	@ResponseBody
    public Map<String,Object>queryByUid(@RequestParam String uid){
        System.out.println("UserController--->queryByUid()");
        Map<String, Object> map = new HashMap<String, Object>();
        List<User> list=userService.queryByUid(uid);
        System.out.println("list:"+list);

        map.put("code", 0);
        map.put("msg", "");
        map.put("data", list);
        return map;
    }
    
    
    
    

	/**
	 * 用户注册
	 */
	@RequestMapping(value="/user/zhuce",produces={"application/json;charset=UTF-8"})//标识方法名称
	@ResponseBody
	@CrossOrigin(origins = "*", maxAge = 3600)
	 public Map<String,Object> zhucefangfa(HttpServletRequest request){
		
        Jedis jedis=new Jedis("127.0.0.1",6379);
        Map<String, Object> map=new HashMap<String, Object>();
        String unumber = request.getParameter("unumber");
        String upassword = request.getParameter("upassword");
        String uname = request.getParameter("uname");
        String usex = request.getParameter("usex");
     
        String yanzhengma = request.getParameter("yanzhengma");
       
        
        System.out.println(unumber+upassword+uname+usex+yanzhengma);


      //从redis中获取的验证码
        String tokenYanzhengma=jedis.get("token");

        //判断验证码
        if(tokenYanzhengma!=null){
            System.out.println("验证码没有过期,用户可以注册");
            if(yanzhengma.equals(tokenYanzhengma)||yanzhengma==tokenYanzhengma){
                System.out.println("验证码正确，注册成功");

                
                User user=new User();
                user.setUid(UUID.randomUUID().toString());
                user.setUname(uname);
                user.setUnumber(unumber);
                user.setUpassword(upassword);
                user.setUsex(usex);
                user.setZhuangtai(UUID.randomUUID().toString());
                
                
             
                System.out.println(user.toString());

                userService.add(user);
                map.put("code", 0);
                map.put("msg", "添加成功");
                return map;
            }
            else{
                System.out.println("输入的验证码错误，请重新输入验证码");
                map.put("login", "0");
                map.put("msg", "输入的验证码错误，请重新输入验证码");
                return map;
            }
        }
        else {
            System.out.println("缓存已经失效,请重新获取验证码");
            map.put("login", "0");
            map.put("msg", "缓存已经失效,请重新获取验证码");
            return map;
        }


    }

    
    
    

    
    
    
    
    
    
}  
    
	
	
	
